package 算法.leetcode.offer;

import 算法.leetcode.offer.base.TreeNode;

/**
 * @author lchenglong
 * @date 2022/3/20
 */
public class Offer55_II {


    public static void main(String[] args) {
        Offer55_II instance = new Offer55_II();
        TreeNode root = TreeNode.init2("1,2,2,3,null,null,3,4,null,null,4");
        boolean balanced = instance.isBalanced(root);
        System.out.println(balanced);
    }
    boolean flag = true;
    public boolean isBalanced(TreeNode root) {
        return Math.abs(dfs(root.left) - dfs(root.right)) <= 1&flag;
    }

    public int dfs(TreeNode root){
        if (root == null)
            return 0;
        else {
            int left = dfs(root.left);
            int right = dfs(root.right);
            if (flag)
                flag = Math.abs(left - right) <= 1;
            return Math.max(left,right)+1;
        }
    }
}
